from flask import request

from api.libs.RedPrint import RedPrint
from core.documents import Ask

api = RedPrint('ask')


@api.route('/count')
def ask_count():
    from core.documents import Ask
    return Ask.objects().count()


@api.route("/clean")
def ask_clean():
    count = int(request.values['count'])
    from core.documents import Ask
    over_count = {}
    for ask in Ask.objects().order_by('-date'):
        if ask.url not in over_count:
            over_count[ask.url] = 0
        over_count[ask.url] += 1
        if over_count[ask.url] > count:
            ask.delete()
    return Ask.objects().count()


@api.route('/list')
def ask_list():
    import time
    import json
    if 'page' not in request.values:
        page = 1
    else:
        page = int(request.values['page'])
    url = request.values['url']
    from core.documents import APIModel, Ask
    model = APIModel.objects(relate_url=url).first()
    query = Ask.objects(url=model.url)
    res = {'count': query.count(), 'data': []}
    asks = query.order_by('-date').skip((page - 1) * 10).limit(10)
    for ask in asks:
        res['data'].append({'key': ask.hash_code,
                            'date': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ask.date)),
                            'params': json.dumps(ask.data)})
    return res


@api.route('/delete')
def ask_delete():
    from core.documents import Ask
    key = request.values['key']
    Ask.objects(hash_code=key).delete()
    return True


@api.route('/detail')
def ask_detail():
    key = request.values['key']
    ask = Ask.objects(hash_code=key).first()
    res = {'params': ask.data, 'result': ask.resp_content.decode()}
    return res


@api.route('/send_again', methods=['POST'])
def send_again():
    import json
    key = request.form['key']
    params = request.form['params']
    ask = Ask.objects(hash_code=key).first()
    try:
        data = json.loads(params)
    except:
        return '请求参数不符合json标准'
    result = ask.send_again(data)
    return result.content.decode()
